<template>
  <div class="social-media">
    <CurrentDate title="Reviews & Reply"></CurrentDate>

    <FilterContainer
      ref="filterContainer"
      @filter-change="handleFilterChange"
      @refresh="getAllReply"
      @filters-applied="handleFiltersApplied"
      @date-change="handleDateChange"
      @sort-change="handleOrderChange"
      :categories="categories"
    ></FilterContainer>

    <!-- ReplyResponeRate组件（监听滚动到一半时固定） -->
    <ReplyResponeRate
      ref="replyResponeRate"
      @platforms-change="handlePlatformsChange"
      :total="pagination.totalItems"
    ></ReplyResponeRate>

    <!-- 父容器作为定位基准 -->
    <div ref="parentContainer" class="parent-container">
      <div
        ref="platCardContainer"
        class="plat-card-container"
        :class="{ 'is-fixed': isFixed }"
        :style="isFixed ? fixedStyle : {}"
      >
        <div
          v-if="!initialRenderComplete"
          style="height: 0; overflow: hidden"
        ></div>
        <showPlatCard
          v-show="showPlatCardVisible && initialRenderComplete"
          ref="showPlatCard"
          :start-date="
            currentFilters.dateRange
              ? formatDate(currentFilters.dateRange[0])
              : ''
          "
          :end-date="
            currentFilters.dateRange
              ? formatDate(currentFilters.dateRange[1])
              : ''
          "
        ></showPlatCard>
      </div>
    </div>

    <MultiInfoReviewCard
      ref="reviewCard"
      :reviews="reviews"
      :is-loading="loading"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.totalItems"
      @page-change="handlePageChange"
    ></MultiInfoReviewCard>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex"; // 关键：导入 mapActions
import { getSentimentReview } from "@/api/information.js";
import CurrentDate from "@components/common/CurrentDate.vue";
import showPlatCard from "./components/showPlatCard.vue";
import FilterContainer from "./components/FilterContainer.vue";
import ReplyResponeRate from "./components/ReplyResponeRate.vue";
import MultiInfoReviewCard from "./components/MultiInfoReviewCard.vue";

const CATEGORY_MAP = {
  Location: "LOCATION_NEIGHBOURHOOD",
  Cleanliness: "CLEANLINESS",
  "Room & Amenities": "ROOM_COMFORT",
  "Hotel Facilities & Amenities": "HOTEL_AMENITIES_ATMOSPHERE",
  "F&B Experience": "FOOD_BEVERAGE",
  Services: "GUEST_EXPERIENCE_SERVICE",
  "Value for Money": "VALUE_FOR_MONEY",
};

export default {
  name: "ReviewReply",
  components: {
    CurrentDate,
    FilterContainer,
    showPlatCard,
    ReplyResponeRate,
    MultiInfoReviewCard,
  },
  data() {
    return {
      categories: {},
      showPlatCardVisible: false,
      loading: false,
      reviews: [],
      pagination: {
        totalItems: 0,
        currentPage: 1,
        pageSize: 10,
      },
      currentFilters: {
        dateRange: null,
        categories: [],
        scoreRange: [1, 10],
        // replyStatuses: [],
        sources: [],
        isReply: undefined,
      },
      selectedPlatforms: [],
      orderBy: "",
      order: "",
      isFixed: false,
      parentRect: null, // 父容器相对视口的位置
      elementRect: null, // 元素相对父容器的偏移
      hasScrolled: false,
      initialCheckDone: false,
      initialRenderComplete: false,
      checkTimeout: null,
      componentTop: 0,
      disableScroll: false,
      scrollPosition: 0,
      isPageChanging: false,
      // 关键：存储ReplyResponeRate一半高度的位置（新的滚动阈值）
      replyRateHalfEdge: 0,
      // 存储ReplyResponeRate的总高度（用于计算一半位置）
      replyRateHeight: 0,
    };
  },
  computed: {
    fixedStyle() {
      if (!this.parentRect || !this.elementRect) return {};
      return {
        width: `${this.elementRect.width}px`,
        left: `${
          this.elementRect.left + this.parentRect.left - window.scrollX
        }px`,
        top: "0px", // 可根据需要调整垂直位置
      };
    },
    currentHotelId() {
      return this.$store.state.hotel.currentHotelId;
    },
  },
  mounted() {
    this.initPlatforms();
    if (this.selectedPlatforms.length) {
      this.getAllReply();
    }
    this.$nextTick(() => {
      this.captureRelativePositions();
      // 计算ReplyResponeRate的一半高度位置（核心修改）
      this.calculateReplyRateHalfEdge();

      this.checkTimeout = setTimeout(() => {
        this.checkVisibility(true);
        this.initialRenderComplete = true;
      }, 50);
      window.addEventListener("scroll", this.handleScroll);
      window.addEventListener("resize", this.handleResize);
    });
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.handleScroll);
    window.removeEventListener("resize", this.handleResize);
    if (this.checkTimeout) clearTimeout(this.checkTimeout);
  },
  methods: {
    captureRelativePositions() {
      const parent = this.$refs.parentContainer;
      const element = this.$refs.platCardContainer;
      if (!parent || !element) return;

      const parentRect = parent.getBoundingClientRect();
      const elementRect = element.getBoundingClientRect();

      this.elementRect = {
        left: elementRect.left - parentRect.left,
        top: elementRect.top - parentRect.top,
        width: elementRect.width,
        height: elementRect.height,
      };
      this.parentRect = parentRect;
    },

    // 核心修改：计算ReplyResponeRate一半高度的位置
    calculateReplyRateHalfEdge() {
      const replyRateEl = this.$refs.replyResponeRate?.$el;
      if (replyRateEl) {
        const rect = replyRateEl.getBoundingClientRect();
        this.replyRateHeight = rect.height; // 总高度
        // 一半位置 = 顶部位置 + 一半高度（相对于文档顶部）
        this.replyRateHalfEdge =
          rect.top + window.scrollY + this.replyRateHeight / 2;
      }
    },

    checkVisibility(initial = false) {
      if (!this.$refs.platCardContainer) return;

      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;

      if (scrollTop <= 0) {
        this.showPlatCardVisible = false;
        return;
      }

      // 关键：滚动距离超过一半高度位置时显示
      this.showPlatCardVisible = scrollTop >= this.replyRateHalfEdge;
    },

    handleResize() {
      this.isFixed = false;
      this.$nextTick(() => {
        this.captureRelativePositions();
        this.calculateReplyRateHalfEdge(); // 重新计算一半位置
        this.handleScroll();
      });
    },

    handleScroll() {
      if (this.disableScroll) return;

      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      this.hasScrolled = true;

      if (this.$refs.parentContainer) {
        this.parentRect = this.$refs.parentContainer.getBoundingClientRect();
      }

      // 关键：滚动超过一半高度位置时固定
      const shouldBeFixed = scrollTop >= this.replyRateHalfEdge;
      if (shouldBeFixed !== this.isFixed) {
        this.isFixed = shouldBeFixed;
      }

      this.checkVisibility();
    },

    // 以下业务逻辑保持不变
    handlePageChange(page) {
      this.isPageChanging = true;
      this.scrollPosition =
        window.pageYOffset || document.documentElement.scrollTop;
      this.pagination.currentPage = page;
      this.getAllReply();
    },

    async getAllSentimentReview(params) {
      this.loading = true;
      try {
        const res = await getSentimentReview(params);
        if (res.code === 200) {
          this.reviews = res.data.page.content || [];
          this.categories = res.data.categoryCounts;
          this.pagination.totalItems = res.data.page.totalElements || 0;
          if (this.reviews.length === 0) {
            this.$message.warning(
              "There are no comments for the moment. Please re-filter"
            );
          }
        } else if (res.code === 401) {
          this.$message.error("Your login has expired. Log in now...");
        } else {
          this.$message.error("Server error. Please try again later");
          this.reviews = [];
          this.pagination.totalItems = 0;
        }
      } catch (error) {
        console.error("Request error:", error);
        this.$message.error("Network error. Please try again later");
        this.reviews = [];
        this.pagination.totalItems = 0;
      } finally {
        this.loading = false;

        if (this.isPageChanging) {
          this.isPageChanging = false;
          this.disableScroll = true;
          window.scrollTo(0, this.scrollPosition);
          setTimeout(() => {
            this.disableScroll = false;
            this.captureRelativePositions();
            this.calculateReplyRateHalfEdge(); // 页面变化后重新计算一半位置
          }, 100);
        }
      }
    },

    initPlatforms() {
      const storePlatforms =
        this.$store.state.reviewReply.selectedPlatforms || [];
      this.selectedPlatforms = storePlatforms
        .filter((p) => p && typeof p === "string")
        .map((p) => p.trim().toUpperCase())
        .filter((p) => p !== "");
      this.currentFilters.sources = [...this.selectedPlatforms];
    },

    handleOrderChange({ orderBy, order }) {
      this.orderBy = orderBy;
      this.order = order;
      this.resetPagination();
    },
    handleFilterChange(filters) {
      this.currentFilters = { ...this.currentFilters, ...filters };
      // 只合并其他筛选条件，排除replyStatuses
      // this.currentFilters = {
      //   ...this.currentFilters,
      //   ...(filters.categories && { categories: filters.categories }),
      //   ...(filters.scoreRange && { scoreRange: filters.scoreRange }),
      //   ...(filters.dateRange && { dateRange: filters.dateRange }),
      // };
      // 删掉原有的replyStatuses解析逻辑
    },
    // handleFilterChange(filters) {
    //   this.currentFilters = { ...this.currentFilters, ...filters };
    //   // 【新增代码】解析 replyStatuses 为 isReply
    //   const { replyStatuses } = filters;
    //   let isReply;
    //   if (
    //     replyStatuses.includes("Replied") &&
    //     !replyStatuses.includes("Pending")
    //   ) {
    //     isReply = true; // 只筛选有回复的
    //   } else if (
    //     !replyStatuses.includes("Replied") &&
    //     replyStatuses.includes("Pending")
    //   ) {
    //     isReply = false; // 只筛选无回复的
    //   } else {
    //     isReply = undefined; // 显示所有（不传递该参数）
    //   }

    //   // 将 isReply 存入 currentFilters，供接口调用时使用
    //   this.currentFilters.isReply = isReply;
    // },

    // handleFiltersApplied(filters) {
    //   this.currentFilters = { ...this.currentFilters, ...filters };
    //   // 【新增代码】解析 replyStatuses 为 isReply
    //   const { replyStatuses } = filters;
    //   let isReply;
    //   if (
    //     replyStatuses.includes("Replied") &&
    //     !replyStatuses.includes("Pending")
    //   ) {
    //     isReply = true;
    //   } else if (
    //     !replyStatuses.includes("Replied") &&
    //     replyStatuses.includes("Pending")
    //   ) {
    //     isReply = false;
    //   } else {
    //     isReply = undefined;
    //   }
    //   this.currentFilters.isReply = isReply;
    //   this.resetPagination();
    //   this.getAllReply();
    // },
    handleFiltersApplied(filters) {
      this.currentFilters = { ...this.currentFilters, ...filters };
      this.resetPagination();
      this.getAllReply();
      // 不再需要解析 replyStatuses
    },
    handlePlatformsChange(platforms) {
      this.selectedPlatforms = platforms
        .filter((p) => p && typeof p === "string")
        .map((p) => p.trim().toUpperCase())
        .filter((p) => p !== "");
      this.currentFilters.sources = [...this.selectedPlatforms];
      this.resetPagination();
    },

    resetPagination() {
      this.pagination.currentPage = 1;
    },

    assembleApiParams(time) {
      if (!this.selectedPlatforms.length) {
        throw new Error("Please select at least one platform");
      }

      const { dateRange } = this.currentFilters;
      if (!dateRange || dateRange.length !== 2) {
        throw new Error("Please select the complete time range");
      }

      const {
        categories = [],
        scoreRange = [1, 10],
        // replyStatuses = [],
      } = this.currentFilters;
      const { isReply } = this.currentFilters;
      const params = {
        hotelId: this.currentHotelId,
        startDate: this.formatDate(dateRange[0]),
        endDate: this.formatDate(dateRange[1]),
        minScore: scoreRange[0],
        maxScore: scoreRange[1],
        orderBy: this.orderBy,
        order: this.order,
        sources: this.selectedPlatforms.join(","),
        page: this.pagination.currentPage - 1,
        size: this.pagination.pageSize,
        ...(isReply !== undefined && { isReply }),
      };

      if (time && this.isValidDateObject(time)) {
        params.timestamp = time.getTime();
        params.formattedDate = this.formatDateObject(time);
      }

      if (categories.length > 0) {
        params.filterCategories = categories
          .map(
            (cat) => CATEGORY_MAP[cat] || cat.toUpperCase().replace(/ /g, "_")
          )
          .join(",");
      }

      // if (replyStatuses.length > 0) {
      //   params.replyStatuses = replyStatuses.join(",");
      // }

      Object.keys(params).forEach((key) => {
        if (params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });

      return params;
    },

    handleDateChange(dateRange) {
      this.currentFilters.dateRange = dateRange;
      this.resetPagination();
    },

    getAllReply(time) {
      try {
        const apiParams = this.assembleApiParams(time);
        this.getAllSentimentReview(apiParams);
      } catch (error) {
        console.error("Parameter assembly failed:", error.message);
        this.$message.warning(error.message);
      }
    },

    formatDateObject(dateObj) {
      if (!(dateObj instanceof Date) || isNaN(dateObj.getTime())) {
        return null;
      }
      const pad = (num) => num.toString().padStart(2, "0");
      return [
        dateObj.getFullYear(),
        pad(dateObj.getMonth() + 1),
        pad(dateObj.getDate()),
      ].join("-");
    },

    isValidDateObject(dateObj) {
      return dateObj instanceof Date && !isNaN(dateObj.getTime());
    },

    formatDate(date) {
      if (!date) return null;
      const d = new Date(date);
      if (isNaN(d.getTime())) return null;
      return [
        d.getFullYear(),
        (d.getMonth() + 1).toString().padStart(2, "0"),
        d.getDate().toString().padStart(2, "0"),
      ].join("-");
    },
  },
};
</script>

<style lang="scss" scoped>
.social-media {
  position: relative;
}

.parent-container {
  width: 100%;
  position: relative;
}

.plat-card-container {
  transition: all 0.3s ease;
  min-height: 1px;
  border-radius: 16px;
  &.is-fixed {
    position: fixed;
    z-index: 1000;
    margin: 0;
    /* 可选：添加背景避免透明重叠 */
    background: white;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }
}

@media (max-width: 768px) {
  .plat-card-container.is-fixed {
    padding: 10px;
    width: calc(100% - 20px) !important;
    left: 10px !important;
  }
}
::v-deep .el-input__inner {
  font-size: 0.125rem;
}
::v-deep .el-pagination .btn-next .el-icon,
::v-deep .el-pagination .btn-prev .el-icon {
  font-size: 0.0972rem;
}
</style>
